namespace Vin.WebApi.Tests.Sse;

public class SseClient : ISseClient
{
    private readonly HttpContext _httpContext;

    public Guid Id { get; } = Guid.NewGuid();

    private HttpResponse Response => _httpContext.Response;

    public SseClient(HttpContext httpContext)
    {
        this._httpContext = httpContext;
        Response.ContentType = "text/event-stream";
        Response.Headers.Append("Cache-Control", "no-cache");
        Response.Headers.Append("Connection", "keep-alive");
    }

    public async Task OpenAsync(Func<HttpContext, ISseClient, Task>? action)
    {
        // 发送当前id给客户端
        await SendAsync(Id.ToString());

        while (!_httpContext.RequestAborted.IsCancellationRequested)
        {
            if (action != null)
            {
                await action(_httpContext, this);
            }
        }
    }

    public async Task SendAsync(string data)
    {
        await Response.WriteAsync($"data: {data}\n\n");
        await Response.Body.FlushAsync();
    }

    public async Task CloseAsync()
    {
    }
}